<script setup>
import {ref, onMounted} from 'vue'
import {ElCard, ElTable, ElTableColumn, ElMessage,ElMessageBox} from 'element-plus'
import {
  getLocationTree,
  getAssetLocationList,
  addAssetLocation,
  deleteAssetLocation,
  getAssetLocationDetail,
  updateAssetLocation
} from "@/api/AssetLocation"

import {Search, Plus, Refresh, Edit, Delete} from '@element-plus/icons-vue'

// 弹框状态
const formVisible = ref(false)
const title = ref('')

// 资产位置表单数据
const locationForm = ref({
  locationName: '',
  parentId: null
})

// 位置树形数据
const parentLocations = ref([])

// 位置列表数据
const locationList = ref([
  {id: 1, locationName: '北京总部', parent: '中国'},
  {id: 2, locationName: '上海分公司', parent: '中国'}
])

// 是否为编辑状态
const isEditMode = ref(false)

// 当前编辑的位置ID
const currentLocationId = ref(null)

// 表单验证规则
const rules = {
  locationName: [
    {required: true, message: '请输入位置名称', trigger: 'blur'}
  ]
}

// 获取资产位置列表数据
const getAssetLocationListData = () => {
  getAssetLocationList().then(res => {
    console.log(res)
    if (res.code === 200) {
      locationList.value = res.data
    }
  })
}

// 提交位置表单
const handleSubmit = () => {
  console.log(locationForm.value, 789)

  // 检查位置名称是否为空
  if (!locationForm.value.locationName) {
    ElMessage.warning('请输入位置名称');
    return;
  }

  const apiMethod = isEditMode.value
      ? updateAssetLocation
      : addAssetLocation;

  const requestData = {
    id: currentLocationId.value,
    locationName: locationForm.value.locationName,
    parentId: locationForm.value.parentId
  };

  apiMethod(requestData).then(res => {
    if (res.code === 200) {
      ElMessage.success(`${isEditMode.value ? '更新' : '新增'}成功`);
      formVisible.value = false;
      resetForm();
      getLocationTreeData();
      getAssetLocationListData()
    }
  });
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  currentLocationId.value = null;
  locationForm.value = {locationName: '', parentId: null};
}

// 新增资产位置
const addAssetLocationData = () => {
  resetForm()
  formVisible.value = true
  title.value = '新增位置'
}

// 获取位置树形结构
const getLocationTreeData = () => {
  getLocationTree().then(res => {
    if (res.code === 200) {
      parentLocations.value = res.data
    }
  })
}

// 删除资产位置
const deleteAssetLocationData = (row) => {
  //console.log(row, "删除")
  ElMessageBox.confirm( '确定删除该资产信息吗?',  '警告',    {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteAssetLocation(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getLocationTreeData()
      }
    }).catch(err => {
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    console.log('取消删除')
  })
}

// 编辑资产位置
const editAssetLocationData = (row) => {
  title.value = '编辑位置'
  // 根据id获取位置详情
  getAssetLocationDetail(row.id).then(res => {
    if (res.code === 200) {
      isEditMode.value = true;
      currentLocationId.value = row.id;
      locationForm.value = {
        locationName: res.data.locationName,
        parentId: res.data.parentId
      }
      formVisible.value = true
    }
  })
}

// 搜索框绑定的位置名称
const queryForm = ref({
  locationName: ''
})

// 按位置名称搜索的方法
const handleSearch = () => {
  // 判断是否为空
  if (!queryForm.value.locationName) {
    ElMessage.warning('请输入位置名称');
    return;
  }
  const params = {
    locationName: queryForm.value.locationName
  }
  console.log(params)
  getAssetLocationList(params).then(res => {
    console.log(res)
    if (res.code === 200) {
      parentLocations.value = res.data
    }
  })
}

// 重置搜索条件
const handleReset = () => {
  queryForm.value.locationName = ''
  getLocationTreeData()
}

onMounted(() => {
  getLocationTreeData()
  //getAssetLocationListData()
})
</script>

<template>

  <!-- 新增搜索框 -->
  <el-form :inline="true" :model="queryForm" style="margin: 10px 0 0 0;">
      <el-form-item>
        <el-space>
          <el-input v-model="queryForm.locationName" placeholder="请输入位置名称" clearable style="width: 300px"
                    :prefix-icon="Search">
            <template #append>
              <el-button type="primary" style="background: #409eff;color: #ffffff;" :icon="Search"
                         @click="handleSearch">
                搜索
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" plain :icon="Refresh" @click="handleReset">
            重置
          </el-button>
          <el-button plain type="primary" :icon="Plus" @click="addAssetLocationData">
            新增
          </el-button>
        </el-space>
      </el-form-item>
  </el-form>


  <el-dialog v-model="formVisible" :title="title" width="30%">
    <el-form :model="locationForm" :rules="rules" label-width="100px">
      <el-form-item label="位置名称" prop="locationName">
        <el-input v-model="locationForm.locationName" placeholder="请输入位置名称" clearable/>
      </el-form-item>
      <el-form-item label="上级位置">
        <!-- 使用级联选择器 -->
        <!-- <el-cascader
          v-model="locationForm.parentId"
          :options="parentLocations"
          :props="{
            value: 'id',
            label: 'locationName',
            children: 'children',
            checkStrictly: true,
            emitPath: false
          }"
          placeholder="请选择上级位置"
          clearable
          :show-all-levels="false"
          popper-class="cascader-popper"
        /> -->
        <el-tree-select
            v-model="locationForm.parentId" placeholder="请选择上级位置"
            :data="parentLocations"
            clearable
            node-key="id"
            :props="{label:'locationName',children:'children'}"
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>
  <el-table
      :data="parentLocations"
      table-layout="auto"
      height="80%"
      style="margin-top: 10px;"
      row-key="id"
      :default-expand-all="false"
  >
    <el-table-column prop="locationName" label="位置名称" align="left"/>
    <el-table-column prop="createTime" label="创建时间" align="center" width="300"/>
    <el-table-column label="操作" align="center" width="180">
      <template #default="scope">
        <el-space>
          <el-link type="primary" :icon="Edit" @click="editAssetLocationData(scope.row)">
          修改
          </el-link>
          <el-link type="danger" :icon="Delete" @click="deleteAssetLocationData(scope.row)">
            删除
          </el-link>
        </el-space>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409EFF;

    &::after {
      content: '（可选）';
      font-size: 12px;
      color: #999;
    }
  }
}
</style>